package com.ruoyi.common.core.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang3.time.DateFormatUtils;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYY_MM_DD_HH = "yyyy-MM-dd hh";

    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     *
     * @param type 类型（0年、1月、2日、3周、4季、5半年）
     * @param time 年份
     * @param number 第几(如：第1半年，第2季，第3月，第4周)
     * @param flag 是否结束日期
     * @return 年月日
     */
    public static Date toDate(int type, String time, int year, @Min(1) @Max(55) int number, boolean flag){
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
        switch (type){
            case 0:
                if (flag){
                    calendar.set(year, Calendar.DECEMBER,31);
                }else {
                    calendar.set(year, Calendar.JANUARY,1);
                }
                break;
            case 1:
                calendar.set(Calendar.YEAR, year);
                if (flag){
                    calendar.set(year, number - 1, 1);
                    int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                    calendar.set(year, number - 1, lastDay);
                }else {
                    calendar.set(Calendar.MONTH, number-1);
                    calendar.set(Calendar.DAY_OF_MONTH, 1);
                }
                break;
            case 2:
                try {
                    return sdf.parse(time);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                break;
            case 3:
                WeekFields weekFields = WeekFields.of(Locale.getDefault());// 获取本地日期的WeekFields
                LocalDate firstDay = LocalDate.of(year, 1, 1)
                        .with(weekFields.weekOfYear(), number)
                        .with(weekFields.dayOfWeek(), 1);// 获取给定年份和周的第一天
                Date date = Date.from(firstDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
                if (flag){
                    calendar.setTime(date);
                    calendar.add(Calendar.DATE, 7);
                }else {
                    return date;
                }
                break;
            case 4:
                if (flag){
                    int month = (number - 1) * 3 + 1; // 计算季度的第一个月份
                    calendar.set(year, month - 1, 1);  // 将日期设置为季度的第一个月的1号
                    int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);  // 获取当月的天数
                    calendar.set(year, month + 1, lastDay);// 将日期设置为季度的最后一个月的最后一天
                }else {
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, (number - 1) * 3);
                    calendar.set(Calendar.DAY_OF_MONTH, 1);
                    calendar.add(Calendar.DAY_OF_YEAR, 0);
                }
                break;
            case 5:
                if (flag){
                    LocalDate date2 = LocalDate.of(year, number == 1 ? Month.JUNE : Month.DECEMBER, 1);
                    LocalDate lastDay = date2.with(TemporalAdjusters.lastDayOfMonth());// 获取这半年的最后一天
                    return Date.from(lastDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
                }else {
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, (number - 1) * 6);
                    calendar.set(Calendar.DAY_OF_MONTH, 1);
                }
                break;
            default:
                break;
        }
        return calendar.getTime();
    }

    /**
     * 获取传入时间那天的第一秒
     */
    public static Date getDayMin(Date date){
        SimpleDateFormat dayFormat = new SimpleDateFormat("yyyyMMdd");
        Date minData = date;
        try {
            minData = dayFormat.parse(dayFormat.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return minData;
    }

    /**
     * 获取传入时间那天的最后一秒
     */
    public static Date getDayMax(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    /**
     * 获取传入时间的前一个月的时间
     */
    public static Date getLastMonth(Date date){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.MONTH, -1);
        return c.getTime();
    }

    /**
     * 获取传入时间的前num个小时,并格式化
     */
    public static String getLastHour(Date date,int num){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.HOUR_OF_DAY, -num);
        return toString(c.getTime());
    }

    public static String toString(Date date){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS);
        LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        return localDateTime.format(formatter);
    }

    public static String toString(Date date,String sdf){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(sdf);
        LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        return localDateTime.format(formatter);
    }

}
